<template>
	<div class="classResources">
		<div class="classIndex_h">
			<span>班级资源</span>
		</div>
		<!--  -->
		<div class="u_resourceH clear">
			<div class="u_resourceH_l fl">
				<router-link :to="{path: '/class/resource/add', query: {id: path}}">上传</router-link>
				<el-button type="primary" @click="statistics()" v-if="resourceList.length > 0">统计</el-button>
				<template v-if="0">
					<el-select filterable v-model="subject_id" placeholder="请选择" @change="changeSelect()">
						<el-option
							v-for="item in subjectList"
							:key="item.id"
							:label="item.name"
							:value="item.id">
						</el-option>
					</el-select>
				</template>
			</div>
			<!--  -->
			<div class="u_resourceH_r fr">
				<el-input
				  size="medium"
				  placeholder="资源名称"
				  suffix-icon="el-icon-search"
				  @change="changeInputName"
				  v-model="resourceName">
				</el-input>
			</div>
		</div>
		<!--  -->
		<ul v-loading="loading">
			<li class="resourceLs clear" v-for="(item, index) in resourceList" :key="item.id">
				<div class="resource_icon fl">
					<img :src="`${BASE_URL}/images/format/resourceicon${item.file_type}.png`">
				</div>
				<div class="resource_txt">
					<div class="resource_link clear">
						<a @click="pathURL(item.id)" target="_blank">{{item.name}}.{{item.postfix}}</a>
						<div class="resource_ioperation fr" v-if="$g.user_id === item.create_id">
							<el-popover
							placement="bottom"
							width=""
							popper-class="ioperation_hover"
							trigger="hover">
							<ul class="r_ioperation">
								<li v-if="item.authority == 0" @click="whetherOpen(item.id)">设为公开</li>
								<li v-if="item.authority != 0" @click="whetherOpen2(item.id)">设为私有</li>
								<li>
									<router-link :to="{path: '/class/resource/edit', query: {id: path ,rid: item.id}}">编辑</router-link>
								</li>
								<li @click="removeList(item.id)">删除</li>
							</ul>
							<i slot="reference" class="el-icon-arrow-down"></i>
						</el-popover>
						</div>
					</div>
					<!--  -->
					<div class="resource_info">
						<button class="r_state1" type="text">{{item.authority == 1 ? '公开' : '不公开'}}</button>
						<span>大小: {{ByteSwitch(item.filesize)}}</span>
						<span>收藏: {{ item.favs }}</span>
						<span>{{item.friend_time}}</span>
					</div>
				</div>
			</li>
		</ul>

		<div class="pageing" v-if="total_number > page_size">
			<el-pagination
			    @current-change="change_page"
			    :page-size="page_size"
			    :current-page="page_index"
			    layout="prev, pager, next"
			    :total="total_number">
			  </el-pagination>
		</div>

		<div class="dependent" v-if="placeholder">
			<i class="ipm image_nofound"></i>
			<p>
				还没发现任何相关的内容哦~
			</p>
		</div>
		<!--  -->
		<transition name="el-fade-in-linear">
			<div class="imasking statisticsBox" :class="{statisticsVisible: isActive}">
				<div class="imak_bg">
					<div class="imak_h">
						<span>资源统计</span>
						<i class="el-icon-close" @click="isActive = false"></i>
					</div>
					<div class="chart" id="chart">
						<IEcharts :option="polar"/>
					</div>
				</div>
			</div>
		</transition>
	</div>
</template>

<script>
	import IEcharts from 'vue-echarts-v3/src/lite.js';
	import 'echarts/lib/chart/pie';
	import 'echarts/lib/component/title';
	import 'echarts/lib/component/legend';

	export default{
		components: {IEcharts },
		data(){
			return {
				path: this.$route.query.id,
				subject_id: '', //学科
				subjectList: this.$g.subjectList,
				resourceList: [],
				page_index: 1,
				page_size: this.$g.page_size,
				total_number: 0,
				resourceName: '', //资源名称
				isActive: false, //统计图
				placeholder: true,
				loading: false,


				statisticsVisible: false, //统计图
				currentPage4: 4,
				polar: {
					backgroundColor: '#fff',
					color: ['#85b6b2', '#6d4f8d', '#cd5e7e', '#e38980', '#f29e29', '#f7db88', '#ffdb6d'],

					title: {
						text: '',
						x: 'right',
						left: '52%',
						top:40,
						textStyle: {
							color: '#6c6c6c',
							fontSize: '14',
						}
					},
					height: { // 图表高度
						type: String,
						default: '250px'
					},
					width: { // 图表宽度
						type: String,
						default: '100%'
					},
					legend: {
						x: 'right',
						left: '52%',
						top:80,
						icon: 'circle',
						data: [],
						formatter: "",
						textStyle: {
							color: '#6c6c6c',
							fontSize: '12',
							width: "300px"
						}
					},
					series: [{
						name: '主题配色下载占比',
						type: 'pie',
						radius: '50%',
						"center": ["25%", "40%"],
						avoidLabelOverlap: false,
						itemStyle: {
							normal: {
								label: {
									show: true,
									// formatter: function(param) {
									// 	console.info(param.name  +  '\n ' + (param.value/1024).toFixed(3))
									// 	return param.name  +  '\n ' + (param.value/1024).toFixed(3) + '%';
									// },
					    		},
					    		labelLine: {
					    			show: false
					    		},
					    		shadowBlur: 40,
					    		shadowColor: 'rgba(40, 40, 40,0.1)',
					    	}
						},
						label: {
							normal: {
								show: false,
								position: 'left'
							},
							emphasis: {
								show: true,
								textStyle: {
									fontSize: '14'
								}
							}
						},
						labelLine: {
							normal: {
								show: true,
							}
						},
						data: []
					}]
				},

			}
		},
		created(){

		},
		watch: {
			/*监听切换班级*/
			'$store.state.changData': {
				handler(val, newval){
					this.path = sessionStorage.getItem('classId')
					this.getResourceList()
				},
				immediate: true
			}
		},
		computed: {

		},
		methods: {
			/*跳转待前台的资源列表*/
			pathURL(id){
				let host = sessionStorage.getItem( 'host' )
				let redirectParams = sessionStorage.getItem( 'redirect_params' )
				let link = `${this.BASE_URL}${redirectParams}&host=${host}&routerUrl=/home/resourceDetail&id=${id}`
				window.open(link)
			},
			/**
			 * 数据列表
			 * @DateTime 2020-03-05T15:41:46+0800
			 * @return   {[type]}                 [description]
			 */
			getResourceList(){
				if( is_empty( this.path) ) {
					return  this.placeholder = true
				}

				this.loading = true;
				let success = (res=>{
					let data = res.data;
					this.resourceList = data.data;
					this.page_index = parseInt(data.page_index);
					this.total_number = data.data_sum;


					this.loading = false
					this.resourceList.length === 0
					? this.placeholder = true
					: this.placeholder = false
				});

				let fail = (res =>{
					return this.loading = false
				});

				this.$ajax({
					url: 'api/org/class_something',
					method: 'get',
					params: {
						style: 2,
						classid: this.path,
						keyword: this.resourceName,
						user_id: this.$g.user_id,
						page: this.page_index,
						size: this.page_size,
						data_type: 2,
						subject_id: this.subject_id,
						
					},
					func: {success: success, fail: fail}
				})
			},
			//分页
			change_page(val){
				this.page_index = val;
				this.getResourceList()
			},
			//筛选
			changeSelect(){
				this.page_index = 1
				this.getResourceList();
			},
			//搜索资源
			changeInputName(){
				this.page_index = 1;
				this.getResourceList()
			},
			//是否公开
			whetherOpen(id){

				this.$confirm('此操作是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					customClass: 'confirm-them'
				}).then(() => {

					let success = (res => {
						this.$message.success(res.msg)
						this.page_index = 1
						this.getResourceList()
					})
					this.$ajax({
						url: '/api/resource/resource',
						method: 'put',
						data: {
							id: id,
							user_id:this.$g.user_id,
							authority: 1
						},
						func:{success:success}
					})
				}).catch(() => {});
			},
			//是否公开
			whetherOpen2(id){
				this.$confirm('此操作是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					customClass: 'confirm-them'
				}).then(() => {

					let success = (res => {
						this.$message.success(res.msg)
						this.page_index = 1
						this.getResourceList()
					})
					this.$ajax({
						url: '/api/resource/resource',
						method: 'put',
						data: {
							id: id,
							user_id:this.$g.user_id,
							authority: 0
						},
						func:{success:success}
					})
				}).catch(() => {});
			},
			//MB单位转换
			ByteSwitch(bytes, decimals){
				bytes = parseInt( bytes );
				decimals = parseInt( decimals );
				if ( decimals > 8 ) {
					decimals = 8;
				}
				if ( isNaN( decimals ) ) {
					decimals = 2;
				}
				var sz = ['B','K', 'M', 'G', 'T', 'P' ];
				var factor = Math.floor( ( ( bytes + '' ).length - 1 ) / 3 );
				var result = bytes / Math.pow( 1024, factor ) + '';
				var index = result.indexOf( '.' );
				if ( index == -1 ) {
					index = result.length - decimals - 1;
				}
				result = result.substr( 0, index + decimals + 1 );
				return result + sz[ factor ];

				var bytes = parseInt(val);

				　if (bytes === 0){ return '0 B'};
				　var k = 1024;
				　var sizes = ['B','KB', 'MB', 'GB', 'TB'];
				　var i = Math.floor(Math.log(bytes) / Math.log(k))　　
				　　//return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
				  var sum = (bytes / Math.pow(k, i)).toPrecision(3)
				　return sum + ' ' + sizes[i];
				　　//toPrecision(3) 后面保留两位小数，如1.00GB
			},
			//删除列表
			removeList(id){
				this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					customClass: 'confirm-them'
				}).then(() => {
					let success = ( res => {
						this.$message.success(res.msg);
						this.page_index = 1;
						this.getResourceList()
					});
					this.$ajax({
						url: 'api/resource/resource',
						method: 'delete',
						params: {
							userid: this.$g.user_id,
							del_type: 0,
							id: id
						},
						func: {
							success: success
						}
					})
				}).catch(() => {});
			},
			//统计表
			statistics(){
				this.getchart()
				this.isActive = true
				
			},
			//资源列表
			getchart(){
				let success = ( res => {
					let data = res.data;
					if (data.length === 0) {
						this.$message.error('暂无相关信息哦~');
						return
					}
					let total = (1024 * 1024 * 1024)*5, //总容量
						proportion = 0,//比例
						number = 0, //使用总数
						bytes = 0  //使用总数

					this.polar.legend.data = data; //文件类型
					this.polar.series[0].data = data; //文件类型数据

					this.polar.series[0].data.forEach( (item) => { //获取文件使用的大小
						item.value = item.file_size
						number += item.file_size ? parseInt(item.file_size) : 0
					});

					//获取文件字节转换对应的大小单位
					bytes = this.ByteSwitch(number) 
					var total_ = this.ByteSwitch(total) 
					proportion = (parseInt( number ) / parseInt( total ) * 100).toPrecision(2);
					this.polar.title.text = `总容量 ${total_}，已使用 ${bytes}，比例 ${proportion}%`;

					//统计表的文件类型所占的比例

					this.polar.legend.formatter  = function(name) {
						var sum = 0;
						var value = 0;
						for(var i = 0; i < data.length; i+=1){
							sum +=  parseInt(data[i].value);
							if(name == data[i].name){

								value = data[i].file_size ? parseInt(data[i].file_size) : 0;
							}
						}
						let sx = value/total * 100
						if (sx === 100) {
							return name + sx.toFixed(0) +'%';
						}else{
							return name + sx.toFixed(3) +'%';
						}
					}
					this.polar.series[0].itemStyle.normal.label.formatter = function(param) {
						var sum = 0;
						var value = 0;
						for(var i = 0; i < data.length; i+=1){
							sum +=  parseInt(data[i].value);
							if(param.name == data[i].name){

								value = data[i].file_size ? parseInt(data[i].file_size) : 0;
							}
						}
						let sx = value/total * 100
						if (sx === 100) {
							return param.name + param.value + sx.toFixed(0) +'%';
						}else{
							return param.name + sx.toFixed(3) +'%';
						}
					}
				});
				this.$ajax({
					url: '/api/org/class_something',
					method: 'get',
					params: {
						classid: this.path,style: 12
					},
					func:{success:success}
				})
			},
		}
	}
</script>